<template>
  <div class="box">
    <div class="header-warpper" @click="$router.back(-1)">
      <img src="../../assets/l_jt.png" alt />
      <span>选择币种</span>
    </div>
    <cube-input v-model="value" placeholder="搜索" class="search-input"></cube-input>
    <div class="list-view" ref="listView">
      <ul>
        <li v-for="group in singers" v-if="group.items.length>0" class="list-group" :key="group.id" ref="listGroup">
          <h2 class="list-group-title" v-if="isseach">{{ group.title }}</h2>
          <ul>
            <li
              v-for="item in group.items"
              @click="confirm({id:item.id,txt:item.name})"
              class="list-group-item"
              :key="item.id"
            >
              <span class="name">{{ item.name }}</span>
            </li>
          </ul>
        </li>
      </ul>
      <div class="list-shortcut" v-if="isseach">
        <ul>
          <li
            v-for="(item, index) in shortcutList"
            class="item"
            :data-index="index"
            :key="item.id"
            @touchstart="onShortcutStart"
            @touchmove.stop.prevent="onShortcutMove"
            :class="{'current': currentIndex === index}"
          >{{ item }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";

export default {
  data() {
    return {
      value: "",
      isseach: true,
      singers1: [],
      singers: [
        { title: "A", items: [] },
        { title: "B", items: [] },
        { title: "C", items: [] },
        { title: "D", items: [] },
        { title: "E", items: [] },
        { title: "F", items: [] },
        { title: "G", items: [] },
        { title: "H", items: [] },
        { title: "I", items: [] },
        { title: "J", items: [] },
        { title: "K", items: [] },
        { title: "L", items: [] },
        { title: "M", items: [] },
        { title: "N", items: [] },
        { title: "O", items: [] },
        { title: "P", items: [] },
        { title: "Q", items: [] },
        { title: "R", items: [] },
        { title: "S", items: [] },
        { title: "T", items: [] },
        { title: "U", items: [] },
        { title: "V", items: [] },
        { title: "W", items: [] },
        { title: "X", items: [] },
        { title: "Y", items: [] },
        { title: "Z", items: [] }
      ],
      scrollY: 0,
      currentIndex: 0
    };
  },
  beforeCreate() {
    this.$axios.post("/index/Mentionaddress/getftype").then(res => {
      var rs = res.data.info;
      for (var i = 0; i < rs.length; i++) {
        for (var j = 0; j < this.singers.length; j++) {
          if (this.singers[j].title == rs[i].name.split("")[0]) {
            this.singers[j].items.push({
              id: rs[i].values,
              name: rs[i].name,
              avatar: ""
            });
          }
        }
      };
      this.singers1 = this.singers;
    });
  },

  created() {
    this.touch = {};
    // 初始化 better-scroll 必须要等 dom 加载完毕
    setTimeout(() => {
      this._initSrcoll();
      this._calculateHeight();
    }, 20);
  },
  methods: {
    confirm(s) {
      this.$router.back(-1);
      sessionStorage.setItem("currency", JSON.stringify(s));
    },
    _initSrcoll() {
      // console.log('didi')
      this.scroll = new BScroll(this.$refs.listView, {
        probeType: 3,
        click: true
      });

      this.scroll.on("scroll", pos => {
        this.scrollY = pos.y;
      });
    },
    onShortcutStart(e) {
      // 获取到绑定的 index
      let index = e.target.getAttribute("data-index");
      // 使用 better-scroll 的 scrollToElement 方法实现跳转
      this.scrollToElement(index);

      // 记录一下点击时候的 Y坐标 和 index
      let firstTouch = e.touches[0].pageY;
      this.touch.y1 = firstTouch;
      this.touch.anchorIndex = index;
    },
    onShortcutMove(e) {
      // 再记录一下移动时候的 Y坐标，然后计算出移动了几个索引
      let touchMove = e.touches[0].pageY;
      this.touch.y2 = touchMove;
      // 这里的 16.7 是索引元素的高度
      let delta = Math.floor((this.touch.y2 - this.touch.y1) / 16.7);

      // 计算最后的位置
      // * 1 是因为 this.touch.anchorIndex 是字符串，用 * 1 偷懒的转化一下
      let index = this.touch.anchorIndex * 1 + delta;
      this.scrollToElement(index);
    },
    scrollToElement(index) {
      // 处理边界情况
      // 因为 index 通过滑动距离计算出来的
      // 所以向上滑超过索引框框的时候就会 < 0，向上就会超过最大值
      if (index < 0) {
        return;
      } else if (index > this.listHeight.length - 2) {
        index = this.listHeight.length - 2;
      }
      // listHeight 是正的， 所以加个 -
      this.scrollY = -this.listHeight[index];
      this.scroll.scrollToElement(this.$refs.listGroup[index]);
    },
    _calculateHeight() {
      this.listHeight = [];
      const list = this.$refs.listGroup;
      let height = 0;
      this.listHeight.push(height);
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        height += item.clientHeight;
        this.listHeight.push(height);
      }
    }
  },
  watch: {
    value(s) {
      if (s) {
        var arrxu = [];
        for (var i = 0; i < this.singers1.length; i++) {
          var ti = this.singers1[i].items;
          for (var j = 0; j < ti.length; j++) {
            if (ti[j].name.includes(s)) {
              arrxu.push({
                id: ti[j].id,
                name: ti[j].name,
                avatar: ""
              });
            }
          }
        }
        this.singers = [];
        this.singers = [
          {
            title: "筛选的",
            items: arrxu
          }
        ];
        this.isseach = false;
      } else {
        this.singers = this.singers1;
        this.isseach = true;
      }
    },
    scrollY(newVal) {
      // 向下滑动的时候 newVal 是一个负数，所以当 newVal > 0 时，currentIndex 直接为 0
      if (newVal > 0) {
        this.currentIndex = 0;
        return;
      }

      // 计算 currentIndex 的值
      for (let i = 0; i < this.listHeight.length - 1; i++) {
        let height1 = this.listHeight[i];
        let height2 = this.listHeight[i + 1];

        if (-newVal >= height1 && -newVal < height2) {
          this.currentIndex = i;
          return;
        }
      }

      // 当超 -newVal > 最后一个高度的时候
      // 因为 this.listHeight 有头尾，所以需要 - 2
      this.currentIndex = this.listHeight.length - 2;
    }
  },
  computed: {
    shortcutList() {
      return this.singers.map(group => {
        return group.title.substr(0, 1);
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search-input {
  background: #f2f4fb;
  height: 1rem;
  padding-left: 0.8rem;
  font-size: 0.4rem;
}
.search-input::after {
  background: url("../../assets/search.png") no-repeat;
  background-size: 1.4rem;
  margin-top: 0.3rem;
  margin-left: 0.4rem;
  border: 0;
}
.header-warpper {
  margin-left: 4%;
  padding-left: 0;
  .f-flex();
  height: 1.333333rem;
  position: relative;
  color: #000;
  img {
    width: 0.213333rem;
    height: 0.373333rem;
  }
  span {
    font-size: 0.48rem;
    padding-left: 0.2rem;
  }
}
.f-flex {
  display: flex;
  display: -webkit-flex;
  align-items: center;
}
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video,
input {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font-weight: normal;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */
article,
aside,
details,
figcaption,
figure,
footer,
header,
menu,
nav,
section {
  display: block;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* custom */
a {
  color: #7e8c8d;
  text-decoration: none;
  -webkit-backface-visibility: hidden;
}

li {
  list-style: none;
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-track-piece {
  background-color: rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 6px;
}

::-webkit-scrollbar-thumb:vertical {
  height: 5px;
  background-color: rgba(125, 125, 125, 0.7);
  -webkit-border-radius: 6px;
}

::-webkit-scrollbar-thumb:horizontal {
  width: 5px;
  background-color: rgba(125, 125, 125, 0.7);
  -webkit-border-radius: 6px;
}

.box {
  position: fixed;
  width: 100%;
  height: 100%;
}
.list-view {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  .list-group {
    padding-bottom: 30px;
    .list-group-title {
      height: 30px;
      line-height: 30px;
      padding-left: 0.3rem;
      font-size: 12px;
      color: black;
      background: #f2f4fb;
      text-align: left;
    }
    .list-group-item {
      display: flex;
      align-items: center;
      padding: 0.46rem 0 0.46rem 0.3rem;
      border-bottom: 1px solid #edeef3;
      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 5%;
      }
      .name {
        color: black;
        font-size: 14px;
        // font-weight: 500;
      }
    }
  }
  .list-shortcut {
    position: absolute;
    z-index: 30;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    padding: 20px 0;
    border-radius: 10px;
    text-align: center;
    background: #fff;
    font-family: Helvetica;
    .item {
      padding: 3px;
      line-height: 1;
      color: black;
      font-size: 11px;
      &.current {
        color: #c20c0c;
        // font-weight: bold;
      }
    }
  }
}
</style>
